/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { CSLine } from '@amcax/base';
import { ctx2 } from '@app-cad/module';

import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import { documentV2 } from '@app-nextmesh/domain';
import { useEffect, useRef, useState } from 'react';
import { Vector3 } from 'three-legacy';
import { createPoint, getNormalsOrIds, removePoint } from '../cmd-common/tools';
import {
  ChildLineCommandProps,
  extraUiSchema,
  FormType,
  Mode,
  PreviewData,
  schema,
} from './type';

export const BetweenSelect = ({ onClose }: ChildLineCommandProps) => {
  const assistGroup = ctx2.cadScene.assisGroup;

  const [formData, setFormData] = useState<FormType>({
    type: Mode.SELECT,
    start: null,
    end: null,
    startInput: null,
    endInput: null,
  });

  const previewData = useRef<PreviewData>({
    line: null,
  });

  const isFormDataValid = () => {
    if (formData.type === Mode.SELECT) {
      return formData.start != null && formData.end != null;
    } else {
      return formData.startInput != null && formData.endInput != null;
    }
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    const startVertext = formData.start?.assisObj.getVertex();
    const endVertext = formData.end?.assisObj.getVertex();

    if (startVertext.distanceTo(endVertext) === 0) {
      MessageTip.error('起点和终点不可重合');
      return;
    }
    let source = null;
    if (formData.type === Mode.SELECT) {
      const ids = getNormalsOrIds([formData.start, formData.end], 'id').map(
        (item) => item.id,
      );
      source = ids;
    } else {
      source = [formData.startInput, formData.endInput];
    }
    try {
      await documentV2.basicCurve({ source, mode: 'segment' });
    } catch (error) {
      //
    }
    onClose();
  };

  // 释放对象
  const releaseObjects = () => {
    previewData.current?.line?.destroy();
    ctx2.cadScene.toolsGroup.clear();
  };

  const { initingEdit } = useCommand('cmd-line-between-dot', {
    releaseObjects,
    onClose,
    finishDraw: checkAndFinishDraw,
  });

  const preview = () => {
    if (isFormDataValid()) {
      let vertexs = null;
      removePoint();
      if (formData.type === Mode.SELECT) {
        vertexs = [
          formData.start?.assisObj?.getVertex(),
          formData.end?.assisObj?.getVertex(),
        ];
      } else if (formData.type === Mode.INPUT) {
        vertexs = [
          new Vector3(...formData.startInput),
          new Vector3(...formData.endInput),
        ];
        createPoint(vertexs);
      }
      if (previewData.current.line == null) {
        previewData.current.line = new CSLine({
          vertexs: vertexs,
          dashed: false,
        });

        previewData.current.line.addTo(assistGroup);
      } else {
        previewData.current.line.update({
          vertexs: vertexs,
        });
      }
    }

    ctx2.viewer.requestRender();
  };
  useEffect(preview, [formData]);
  return (
    <NonDialogPickableCommandForm
      className='-mt-3'
      disabled={initingEdit}
      schema={schema}
      onCancel={onClose}
      formData={formData}
      onChange={(v) => {
        setFormData((state) => {
          if (v.type == Mode.SELECT) {
            return {
              type: v.type,
              start: v.start,
              end: v.end,
              startInput: v.start?.assisObj?.getVertex()?.toArray(),
              endInput: v.end?.assisObj?.getVertex()?.toArray(),
            };
          } else {
            return {
              ...state,
              type: v.type,
              startInput: v.startInput,
              endInput: v.endInput,
            };
          }
        });
      }}
      extraUiSchema={extraUiSchema}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={(() => {
        return isFormDataValid();
      })()}
    />
  );
};
